﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC4App.Areas.Administrators.Models;
using MVC4App.Code;
using MVC4App.Repositories.Core.Security;
using MVC4App.Repositories.Implementations.Security;
using Newtonsoft.Json;

namespace MVC4App.Areas.Administrators.Controllers
{
    public class AdminBaseController : Controller
    {
        private readonly ISiteRepository _siteRepository;
        private readonly IPermissionRepository _permissionRepository;
        protected int UserId;
        protected int SiteId=0;
        protected int PerId=0;
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {            
            var o = Session["UserId"];
            if (o == null)
            {
                filterContext.Result = Redirect(UrlMaker.ToLogin());
            }
            else
            {
                int.TryParse(o.ToString(), out UserId);
                var siteIdParam = RouteData.Values["siteId"];
                var perIdParam = RouteData.Values["perId"];   
                if(perIdParam!=null && PerId==0)
                {                    
                    int.TryParse(perIdParam.ToString(), out PerId);                    
                }   
                if (siteIdParam != null && SiteId==0)
                {                                    
                    int.TryParse(siteIdParam.ToString(), out SiteId);
                    if(SiteId>0)
                    {                        
                        var pers = _permissionRepository.GetListByUserAndSite(UserId, SiteId);
                        if(pers.Count>0)
                        {
                            ViewBag.PermissionJson = JsonConvert.SerializeObject(pers);
                        }                        
                    }
                }
            }
            base.OnActionExecuting(filterContext);
        }
        public AdminBaseController()
        {
            _siteRepository = new SiteRepository();
            _permissionRepository = new PermissionRepository();
        }
        public virtual ActionResult Index(int? siteId = 0)
        {
            if (siteId > 0)
            {                
                var obj = _siteRepository.Get((int)siteId);
                return View(obj.ToModel());
            }
            return View("Error");
        }
    }
}
